package com.cheyun.netsalev3.tencenttim.chat;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.tencenttim.helper.ChatLayoutHelper;
import com.cheyun.netsalev3.tencenttim.helper.CustomAVCallUIController;
import com.cheyun.netsalev3.tencenttim.helper.TRTCListener;
import com.cheyun.netsalev3.tencenttim.profile.MyInfoActivity;
import com.cheyun.netsalev3.tencenttim.signature.GenerateTestUserSig;
import com.cheyun.netsalev3.tencenttim.utils.Constants;
import com.cheyun.netsalev3.tencenttim.utils.DemoLog;
import com.cheyun.netsalev3.utils.MyAudioPlayer;
import com.cheyun.netsalev3.utils.api.DmApiClient;
import com.cheyun.netsalev3.utils.api.DmBaseResp;
import com.cheyun.netsalev3.utils.api.dm.DmApiCallback;
import com.cheyun.netsalev3.utils.api.dm.DmApiException;
import com.cheyun.netsalev3.widget.CircleImageView;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMManager;
import com.tencent.qcloud.tim.uikit.base.BaseFragment;
import com.tencent.qcloud.tim.uikit.component.AudioPlayer;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.ChatLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.message.MessageLayout;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;

import org.jetbrains.annotations.NotNull;

import androidx.annotation.Nullable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.tencent.trtc.TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL;
import static com.tencent.trtc.TRTCCloudDef.TRTC_TranscodingConfigMode_Template_PureAudio;


public class ChatFragment extends BaseFragment {

    private static final String TAG = ChatFragment.class.getSimpleName();

    private View mBaseView;
    private ChatLayout mChatLayout;
    private TitleBarLayout mTitleBar;
    private ChatInfo mChatInfo;
//    private int chatType;
//    private int roomId;

    private TextView title;
    private TextView leftBut;
    private ImageView rightImg;

    //call
    private LinearLayout ly_call;
    private CircleImageView call_face;
    private TextView tv_name;
//    private TextView tv_tel;
    private ImageView iv_hangup;
    private RelativeLayout rl_video;
    private ImageView iv_lb;
    private ImageView iv_kg;
    private ImageView iv_qh;

    private TXCloudVideoView mLocalPreviewView;
    private TXCloudVideoView mSubVideoView;

    private boolean laba = true;
    private boolean qh = true;
    private boolean kg = false;

    private TRTCCloud mTRTCCloud;
    private TRTCCloudDef.TRTCParams mTRTCParams;
    private TRTCCloudListener mTRTCCloudListener = new TRTCCloudListener() {

        @Override
        public void onError(int errCode, String errMsg, Bundle extraInfo) {
            DemoLog.i(TAG, "onError " + errCode + " " + errMsg);
            closeChat();
        }

        @Override
        public void onExitRoom(int reason) {
            super.onExitRoom(reason);
            DemoLog.i(TAG, "onExitRoom " + reason);
            closeChat();
        }

        @Override
        public void onRemoteUserEnterRoom(String userId) {
            super.onRemoteUserEnterRoom(userId);
            DemoLog.i(TAG, "onRemoteUserEnterRoom " + userId);
        }

        @Override
        public void onRemoteUserLeaveRoom(String userId, int reason) {
            super.onRemoteUserLeaveRoom(userId, reason);
            DemoLog.i(TAG, "onRemoteUserLeaveRoom " + userId + " " + reason);
            // 对方超时掉线
            if (reason == 1) {
                finishVideoCall();
                closeChat();
            }
        }

        @Override
        public void onFirstVideoFrame(String userId, int steamType, int width, int height) {
            DemoLog.i(TAG, "onFirstVideoFrame " + userId + " " + steamType + " " + width + " " + height);
            super.onFirstVideoFrame(userId, steamType, width, height);
            if (!TextUtils.equals(userId, TIMManager.getInstance().getLoginUser())) {
                ViewGroup.LayoutParams params = mSubVideoView.getLayoutParams();
                final int FIXED = 480;
                params.width = FIXED;
                params.height = FIXED * height / width;
                mSubVideoView.setLayoutParams(params);
            }
        }

        @Override
        public void onUserVideoAvailable(String userId, boolean available) {
            super.onUserVideoAvailable(userId, available);
            DemoLog.i(TAG, "onUserVideoAvailable " + userId + " " + available);
            if (available) {
                mTRTCCloud.setRemoteViewFillMode(userId, TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FIT);
                mTRTCCloud.startRemoteView(userId, mSubVideoView);
            }
        }
    };

//    private TRTCCloudDelegate

    public static final String KEY_ROOM_ID = "room_id";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        mBaseView = inflater.inflate(R.layout.chat_fragment, container, false);
        return mBaseView;
    }

    private void initView() {
        //从布局文件中获取聊天面板组件
        mChatLayout = mBaseView.findViewById(R.id.chat_layout);

        //单聊组件的默认UI和交互初始化
        mChatLayout.initDefault();

        /*
         * 需要聊天的基本信息
         */
        mChatLayout.setChatInfo(mChatInfo);

        //获取单聊面板的标题栏
        mTitleBar = mChatLayout.getTitleBar();
        mTitleBar.setVisibility(View.GONE);
        //单聊面板标记栏返回按钮点击事件，这里需要开发者自行控制
//        mTitleBar.setOnLeftClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                getActivity().finish();
//            }
//        });
        title = mBaseView.findViewById(R.id.titleText);
        leftBut = mBaseView.findViewById(R.id.leftBut);
        rightImg = mBaseView.findViewById(R.id.rightImg);
        leftBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyAudioPlayer.getInstance().stopPlay();
                getActivity().finish();
            }
        });
        title.setText(mChatInfo.getChatName());
        if (mChatInfo.getType() == TIMConversationType.C2C) {
//            mTitleBar.setOnRightClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent(MyApplication.getInstance(), FriendProfileActivity.class);
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    intent.putExtra(TUIKitConstants.ProfileType.CONTENT, mChatInfo);
//                    MyApplication.getInstance().startActivity(intent);
//                }
//            });
            rightImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Intent intent = new Intent(MyApplication.getInstance(), FriendProfileActivity.class);
                    Intent intent = new Intent(MyApplication.getInstance(), MyInfoActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(TUIKitConstants.ProfileType.CONTENT, mChatInfo);
                    MyApplication.getInstance().startActivity(intent);
                }
            });
        }

        mChatLayout.getMessageLayout().setOnItemClickListener(new MessageLayout.OnItemClickListener() {
            @Override
            public void onMessageLongClick(View view, int position, MessageInfo messageInfo) {
                //因为adapter中第一条为加载条目，位置需减1
                mChatLayout.getMessageLayout().showItemPopMenu(position - 1, messageInfo, view);
            }

            @Override
            public void onUserIconClick(View view, int position, MessageInfo messageInfo) {
//                if (null == messageInfo) {
//                    return;
//                }
//                ChatInfo info = new ChatInfo();
//                info.setId(messageInfo.getFromUser());
//                Intent intent = new Intent(MyApplication.getInstance(), FriendProfileActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.putExtra(TUIKitConstants.ProfileType.CONTENT, info);
//                MyApplication.getInstance().startActivity(intent);
            }
        });

        ly_call = mBaseView.findViewById(R.id.ly_call);
        call_face = mBaseView.findViewById(R.id.call_face);
        tv_name = mBaseView.findViewById(R.id.tv_name);
//        tv_tel = mBaseView.findViewById(R.id.tv_tel);
        iv_hangup = mBaseView.findViewById(R.id.iv_hangup);
        rl_video = mBaseView.findViewById(R.id.rl_video);
        iv_lb = mBaseView.findViewById(R.id.iv_lb);
        iv_kg = mBaseView.findViewById(R.id.iv_kg);
        iv_qh = mBaseView.findViewById(R.id.iv_qh);

    }

    @Override
    public void onResume() {
        super.onResume();

        Bundle bundle = getArguments();
        mChatInfo = (ChatInfo) bundle.getSerializable(Constants.CHAT_INFO);
        if (mChatInfo == null) {
            return;
        }
//        chatType = bundle.getInt(Constants.CHAT_TYPE,0);
//        roomId = bundle.getInt(Constants.ROOM_ID,0);

        initView();

//        if(chatType>0) {
//            initCall();
//        }
        // TODO 通过api设置ChatLayout各种属性的样例
        ChatLayoutHelper helper = new ChatLayoutHelper(getActivity());
        helper.customizeChatLayout(mChatLayout);
    }

    @Override
    public void onPause() {
        super.onPause();
        AudioPlayer.getInstance().stopPlay();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mChatLayout != null) {
            mChatLayout.exitChat();
        }
        TRTCListener.getInstance().removeTRTCCloudListener(mTRTCCloudListener);
    }

    public void startCall(int roomId,int chatType){
        initCall(roomId,chatType);
    }

    private void initCall(int roomId,int chatType){
        //语音视频窗口相关设置
        if(chatType == 0){
            ly_call.setVisibility(View.GONE);
        }else{
            ly_call.setVisibility(View.VISIBLE);
            tv_name.setText(mChatInfo.getChatName());
//            tv_tel.setText(mChatInfo.getChatName());
            iv_hangup.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closeChat();
                    finishVideoCall();
                }
            });

            iv_lb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    laba = !laba;
                    if(laba){
                        mTRTCCloud.startLocalAudio();
                    }else{
                        mTRTCCloud.stopLocalAudio();
                    }

                    iv_lb.setImageDrawable(getResources().getDrawable((laba ?R.drawable.fjy_tb:R.drawable.jy_tb)));
                }
            });

            iv_kg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    kg = !kg;
//                    if(kg){
//                        mTRTCCloud.startLocalPreview ();
//                    }else{
//                        mTRTCCloud.stopLocalPreview();
//                    }
//                    if(kg){
//                        mTRTCCloud.startLocalPreview(mLocalPreviewView);
//                    }else{
//                        mTRTCCloud.stopLocalPreview();
//                    }
                    mTRTCCloud.muteLocalVideo(kg);
                    iv_kg.setImageDrawable(getResources().getDrawable((kg ?R.drawable.spjzck_tb:R.drawable.spyxck_tb)));
                }
            });
            iv_qh.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mTRTCCloud.switchCamera();
                }
            });
            if(chatType == 1){
                rl_video.setVisibility(View.VISIBLE);
            }else{
                rl_video.setVisibility(View.GONE);
            }
        }

        this.getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        this.getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mLocalPreviewView = mBaseView.findViewById(R.id.local_video_preview);
        mSubVideoView = mBaseView.findViewById(R.id.sub_video);

        // 获取进房参数
//        int roomId = getIntent().getIntExtra(KEY_ROOM_ID, 0);
        DemoLog.i(TAG, "enter room id: " + roomId);
        int sdkAppId = GenerateTestUserSig.SDKAPPID;
        String userId = TIMManager.getInstance().getLoginUser();
        String userSig  = GenerateTestUserSig.genTestUserSig(userId);
        mTRTCParams = new TRTCCloudDef.TRTCParams(sdkAppId, userId, userSig, roomId, "", "");
        //appid_roomId_username_streamNo
        String streamId = GenerateTestUserSig.SDKAPPID+"_"+roomId + "_"+ userId+"_"+ CustomAVCallUIController.getInstance().getStreamNo();
        mTRTCParams.streamId = streamId;
        mTRTCCloud = TRTCCloud.sharedInstance(this.getActivity());

        laba = true;
        mTRTCCloud.startLocalAudio();

        if(chatType == 2){
            mTRTCCloud.stopLocalPreview();
        }else if(chatType == 3){
            kg = false;
            mTRTCCloud.muteLocalVideo(kg);
        }
        DmApiClient.INSTANCE.getInstance().kefuRunningAdd(userId,mChatInfo.getChatName())
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new DmApiCallback<DmBaseResp<Object, Object>>() {
                    @Override
                    protected void onSuccess(DmBaseResp<Object, Object> t) {
                        DemoLog.i(TAG, "add kefu success" );
                    }

                    @Override
                    protected void onError(@NotNull DmApiException ex) {
                        DemoLog.i(TAG, "add kefu fail" );
                    }
                });
        enterRoom();
    }

    private void enterRoom() {
        TRTCListener.getInstance().addTRTCCloudListener(mTRTCCloudListener);
        mTRTCCloud.setListener(TRTCListener.getInstance());
        mTRTCCloud.startLocalAudio();
        mTRTCCloud.startLocalPreview(true, mLocalPreviewView);
        mTRTCCloud.enterRoom(mTRTCParams, TRTC_APP_SCENE_VIDEOCALL);
        mTRTCCloud.enableAudioEarMonitoring(false);

        TRTCCloudDef.TRTCTranscodingConfig trtcTranscodingConfig = new TRTCCloudDef.TRTCTranscodingConfig();
        trtcTranscodingConfig.appId = GenerateTestUserSig.SDKAPPID;
        trtcTranscodingConfig.mode = TRTC_TranscodingConfigMode_Template_PureAudio;
        mTRTCCloud.setMixTranscodingConfig(trtcTranscodingConfig);
    }

    public void finishVideoCall() {
        CustomAVCallUIController.getInstance().hangup();
        CustomAVCallUIController.getInstance().exitRoom();
        if(mTRTCCloud!=null) {
            mTRTCCloud.exitRoom();
        }
        ly_call.setVisibility(View.GONE);
    }

    private void closeChat(){
        this.getActivity().finish();
    }
}
